<?php

namespace App\Console\Commands;

use App\Common\WebSocketClient;
use App\Http\Controllers\ApiController;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

//use JsonRPC\Server;

class TestRpc extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test:rpc';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
//        go(function () {
//            $cli = new \Co\http\Client("127.0.0.1", 8802);
//            $ret = $cli->upgrade("/");
//            if ($ret) {
//                while(true) {
//                    $cli->push("hello4tetret");
//                    var_dump($cli->recv());
//                    \co::sleep(0.1);
//                }
//            }
//        });

//        $client = new \swoole_client(SWOOLE_SOCK_TCP);
//        if (!$client->connect('127.0.0.1', 8802,-1))
//        {
//            exit("connect failed. Error: {$client->errCode}\n");
//        }
//        $client->send("hello worldrtryr\n");
//        echo $client->recv();
//        $client->close();


        $wsc = new WebSocketClient("127.0.0.1", 8802);
        $wsc->connect();
        $wsc->send("hello worldeeee\n");
        echo $wsc->recv();
        $wsc->close();

//        Redis::subscribe('channel1',function ($msg,$channel)use($wsc){
//            $data = json_decode($msg,true);
//            $data['subscribe'] = 1;
//            $wsc->send(json_encode($data));
//        });
    }

    public function get($url, $header = [])
    {
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (!empty($header))
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_TIMEOUT, 10);

        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        dd($aStatus);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }
}
